package com.asia5b.a5mall.middleware.config

import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * Created by zhangyuncai on 2020/4/10.
 */
object TimerHelper {

    val disposableList = arrayListOf<Disposable>()
    val timeLengh = 60L

    /**
     * @param countDown倒计时
     * @param isRemoveBefore 是否移除之前的倒计时 , 默认移除
     */
    fun timer(callback: (countDown: Int) -> Unit, isRemoveBefore: Boolean = true): Disposable {
        if (isRemoveBefore) {
            for (disposable in disposableList) {
                if (!disposable.isDisposed) {
                    disposable.dispose()
                }
            }
        }

        var disposable = Observable.intervalRange(0, timeLengh, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer {
                    callback.invoke((timeLengh - it - 1).toInt())
                }, Consumer {
                    it.printStackTrace()
                })
        disposableList.add(disposable)
        return disposable
    }
}